package org.advanced.expand;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author John.zhang
 * @version Id: TransAccountB, v 1.0 2020/12/11 17:18 ZhiYong Exp $
 * Lock破坏死锁(破坏不可抢占)
 */
public class TransAccountB implements Runnable {

    private Account fromAccount;

    private Account toAccount;

    private int amount;

    ReentrantLock fromLock = new ReentrantLock();

    ReentrantLock toLock = new ReentrantLock();

    public TransAccountB(Account fromAccount, Account toAccount, int amount) {
        this.fromAccount = fromAccount;
        this.toAccount = toAccount;
        this.amount = amount;
    }

    @Override
    public void run() {
        while (true) {
            if (fromLock.tryLock()) {
                if (toLock.tryLock()) {
                    if (fromAccount.getBalance() >= amount) {
                        fromAccount.debit(amount);
                        toAccount.credit(amount);
                    }
                    System.out.println(fromAccount.getAccountName() + "-" + fromAccount.getBalance());
                    System.out.println(toAccount.getAccountName() + "-" + toAccount.getBalance());
                }
            }
        }
    }


    public static void main(String[] args) {
        Account fromAccount = new Account("张三", 100000);
        Account toAccount = new Account("李四", 200000);

        Thread threadA = new Thread(new TransAccountB(fromAccount, toAccount, 1));
        Thread threadB = new Thread(new TransAccountB(toAccount, fromAccount, 1));
        threadA.start();
        threadB.start();
    }

}
